﻿@model IEnumerable<JewererBasic.STONE>

@{
    ViewBag.Title = "Stone Management";

    var gd = new WebGrid(
            Model,
            canPage: true,
            rowsPerPage: 10,
            selectionFieldName: "selectedRow",
            ajaxUpdateContainerId: "gridContent"
        );
    gd.Pager(WebGridPagerModes.NextPrevious);
}

<h2>Stone Management</h2>

@using (Html.BeginForm())
{
    <fieldset>
        <table>
            <tr>
                <td>
                    <table>
                        <tr>
                            <td>
                                <a href="/Stone/Import">
                                    <input type="button" value="IMPORT" />
                                </a>
                            </td>
                            <td>
                                <a href="/Stone/TestingExportList">
                                    <input type="button" value="STAFF EXP" />
                                </a>
                            </td>
                            <td>
                                <a href="/Stone/BagExport">
                                    <input type="button" value="BAG EXP" />
                                </a>
                            </td>
                            <td>
                                <a href="/Stone/History">
                                    <input type="button" value="HISTORY" />
                                </a>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td></td>
            </tr>
            <tr>
                <td>
                    <fieldset>
                        <legend>ADD NEW STONEs</legend>
                        <div>
                            <input type="button" value="ADD" id="btnAddNewRow" />
                            <input type="button" value="FINISH" id="btnAddMore" />
                            <input type="button" value="CLEAR" id="btnClear" />
                        </div>
                        <div style="height: 25px"></div>
                        <div>
                            <div id="contentPaste" contenteditable="true">Paste copied items in here...</div>
                        </div>
                        <fieldset id="myfieldset">
                            <legend>STONEs</legend>
                            <p id="notification" style="color: red; display: none"></p>
                            <div id="stoneArea" />
                        </fieldset>
                    </fieldset>
                </td>
            </tr>
            <tr>
                <td>
                    <fieldset>
                        <div>
                            <fieldset>
                                <legend>SEARCH</legend>
                                <table>
                                    <tr>
                                        <td style="text-align: center">
                                            <strong>Item</strong>
                                        </td>
                                        <td style="text-align: center">
                                            <strong>Name</strong>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            @Html.TextBox("txtSearchId", "", new { placeholder = "Stone Id", title = "Input Stone Id.", @class = "textInput" })
                                        </td>
                                        <td>
                                            @Html.TextBox("txtSearchName", "", new { placeholder = "Stone Name", title = "Input Stone Name.", @class = "textInput" })
                                        </td>
                                        <td>
                                            <input type="submit" name="submit" id="submitAdd" value="SEARCH" />
                                        </td>
                                    </tr>
                                </table>
                            </fieldset>
                        </div>

                        <div id="stoneListDiv">
                            @gd.GetHtml(
                            tableStyle: "table",
                            headerStyle: "head",
                            rowStyle: "row",
                            alternatingRowStyle: "altRow",
                            selectedRowStyle: "selectRow",
                            columns: gd.Columns(
                            gd.Column(header: "Stone Id", format: @<div style="width: 200px; text-align: center;"><span><span id="spanId_@item.Id">@item.Id</span></span></div>),
                            gd.Column(header: "Name", format: @<div style="width: 200px; text-align: center;"><span><span id="spanName_@item.Id">@item.Name</span>@Html.TextBox("Name_" + (string)item.Id, (string)item.Name, new { @style = "display:none; width: 120px" })</span></div>),
                            gd.Column(header: "Description", format: @<div style="width: 150px; text-align: center;"><span><span id="spanDescription_@item.Id">@item.Decription</span>@Html.TextBox("Description_" + (string)item.Id, (string)item.Decription, new { @style = "display:none; width: 120px" })</span></div>),
                            gd.Column(header: "Type", format: @<div style="width: 100px; text-align: center;"><span><span id="spanType_@item.Id">@(item.TYPE == null ? "" : item.TYPE.Name)</span>@Html.DropDownList("Type_" + (string)item.Id, new SelectList(@ViewBag.Types, "Id", "Name", @item.IdType), "None", new { @style = "display:none; width: 120px" })</span></div>),
                            gd.Column(header: "Unit", format: @<div style="width: 100px; text-align: center;"><span><span id="spanUnit_@item.Id">@item.UNIT.Name</span>@Html.DropDownList("Unit_" + (string)item.Id, new SelectList(@ViewBag.Units, "Id", "Name", @item.IdUnit), "None", new { @style = "display:none; width: 120px" })</span></div>),
                            gd.Column(header: "Weight", format: @<div style="width: 100px; text-align: center;"><span><span id="spanWeight_@item.Id">@item.Weight</span></span></div>),
                            gd.Column(header: "Quantity", format: @<div style="width: 100px; text-align: center;"><span><span id="spanQuantity_@item.Id">@item.Numb</span></span></div>),
                            gd.Column(header: "Action", format: @<div style="width: 150px; text-align: center;"><a href="#" id="Edit_@item.Id" style="margin: 5px" class="edit">Edit</a><a href="#" id="Update_@item.Id" style="display:none; margin: 5px" class="update">Update</a><a href="#" id="Cancel_@item.Id" style="display:none; margin: 5px" class="cancel">Cancel</a></div>)
                        ))
                        </div>
                    </fieldset>
                </td>
            </tr>
        </table>
    </fieldset>
}

@section Scripts {
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script src="@Url.Content("~/Scripts/json2.min.js")" type="text/javascript"></script>

    <script type="text/javascript">

        $("#txtId").blur(function () {
            var id = $(this).val();

            $.ajax({
                url: '/Stone/IsStoneExisted',
                data: { "id": id },
                dataType: 'json',
                type: 'GET',
                success: function (data) {
                    if (data.result == true) {
                        $("#errorAdd").text("Stone id has alreadly existed in the system.").show().fadeOut(5000);
                    }
                },
                error: function (xhr, errorType, exception) {

                }
            });
        });

        $("#addStone").click(function () {

            var id = $("#txtId").val();
            var name = $("#txtName").val();
            var description = $("#txtDescription").val();
            var type = $("#ddlType option:selected").val();
            var typeName = $("#ddlType option:selected").text();
            var unit = $("#ddlUnit option:selected").val();
            var unitName = $("#ddlUnit option:selected").text();
            var weight = $("#txtWeight").val();
            var quantity = $("#txtQuantity").val();

            var idRequired = "Stone Id";
            //var nameRequired = "Stone Name";
            var typeRequired = "Type";
            var unitRequired = "Unit";
            var errorText = "Some required fields: ";
            var isHasError = false;

            if (id.length == 0) {
                $("#txtId").focus();
                errorText += idRequired;
                isHasError = true;
            }
            /*
            if (name.length == 0) {
                if (isHasError == true) {
                    errorText += ", ";
                } else {
                    $("#txtName").focus();
                }
                errorText += nameRequired;
                isHasError = true;
            }
            */
            if (type.length == 0) {
                if (isHasError == true) {
                    errorText += ", ";
                } else {
                    $("#ddlType").focus();
                }
                errorText += typeRequired;
                isHasError = true;
            }
            if (unit.length == 0) {
                if (isHasError == true) {
                    errorText += ", ";
                } else {
                    $("#ddlUnit").focus();
                }
                errorText += unitRequired;
                isHasError = true;
            }

            if (isHasError == true) {
                errorText += ".";
                $("#errorAdd").text(errorText);
                $("#errorAdd").show();
            } else {
                if (weight.length == 0) {
                    weight = 0;
                }
                if (quantity.length == 0) {
                    quantity = 0;
                }

                $.ajax({
                    url: '/Stone/IsStoneExisted',
                    data: { "id": id },
                    dataType: 'json',
                    type: 'GET',
                    success: function (data) {
                        if (data.result == true) {
                            $("#errorAdd").text("Stone id has alreadly existed in the system.").show();
                            $("#txtId").focus();
                        } else {
                            $.ajax({
                                url: '/Stone/AddStone',
                                data: { "id": id, "name": name, "description": description, "typeId": type, "unitId": unit, "weight": weight, "quantity": quantity },
                                dataType: 'json',
                                type: 'GET',
                                success: function (data) {
                                    if (data.result == true) {
                                        $("#errorAdd").text("Add stone successfully.").show().fadeOut(5000);

                                        // add stone to table
                                        var className = $("#stoneListDiv").find("tbody").find("tr:last").hasClass("row");

                                        if (className == true) {
                                            className = "altRow";
                                        } else {
                                            className = "row";
                                        }

                                        var newRow = '<tr class="' + className + '"><td><div id="spanId_' + id + '" style="width: 200px; text-align: center;">' + id + '</div></td>'
                                            + '<td><div style="width: 200px; text-align: center;"><span id="spanName_' + id + '">' + name + '</span><input id="Name_' + id + '" style="display:none; width: 120px" type="text"></div></td>'
                                            + '<td><div style="width: 150px; text-align: center;"><span id="spanDescription_' + id + '">' + description + '</span><input id="Description_' + id + '" style="display:none; width: 120px" type="text"></div></td>'
                                            + '<td><div id="spanId_' + id + '" style="width: 100px; text-align: center;">' + typeName + '</div></td>'
                                            + '<td><div id="spanId_' + id + '" style="width: 100px; text-align: center;">' + unitName + '</div></td>'
                                            + '<td><div id="spanId_' + id + '" style="width: 100px; text-align: center;">' + weight + '</div></td>'
                                            + '<td><div id="spanId_' + id + '" style="width: 100px; text-align: center;">' + quantity + '</div></td>'
                                            + '<td><div style="width: 150px; text-align: center;"><a href="#" id="Edit_' + id + '" style="margin: 5px" class="edit">Edit</a><a href="#" id="Update_' + id + '" style="display:none; margin: 5px" class="update">Update</a><a href="#" id="Cancel_' + id + '" style="display:none; margin: 5px" class="cancel">Cancel</a></div></td>' + "</tr>";

                                        $("#stoneListDiv").find("table tbody:last").append(newRow);

                                        $("#txtId").val("");
                                        $("#txtName").val("");
                                        $("#txtDescription").val("");
                                        $("#txtWeight").val("");
                                        $("#txtQuantity").val("");

                                        $("#ddlType option:selected").removeAttr("selected");
                                        $("#ddlUnit option:selected").removeAttr("selected");
                                    } else {
                                        $("#errorAdd").text("Stone id has alreadly existed in the system.").show().fadeOut(5000);
                                    }

                                },
                                error: function (xhr, errorType, exception) {
                                    $("#errorAdd").text("Some unexpected error occurred.").show().fadeOut(5000);
                                }
                            });
                        }
                    },
                    error: function (xhr, errorType, exception) {

                    }
                });
            }
        });

        $("#txtSearchId").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '/Stone/GetStones',
                    data: { query: request.term },
                    dataType: 'json',
                    type: 'GET',
                    success: function (data) {
                        response($.map(data, function (item) {
                            return {
                                label: item,
                                value: item
                            }
                        }));
                    },
                })
            },
            messages: {
                noResults: '',
                results: function () { }
            },
            select: function (event, ui) {
                $("#txtSearchId").val(ui.item.label);
                return false;
            },
            minLength: 1
        });

        $("#txtSearchName").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '/Stone/GetStoneNames',
                    data: { query: request.term },
                    dataType: 'json',
                    type: 'GET',
                    success: function (data) {
                        response($.map(data, function (item) {
                            return {
                                label: item,
                                value: item
                            }
                        }));
                    },
                })
            },
            messages: {
                noResults: '',
                results: function () { }
            },
            select: function (event, ui) {
                $("#txtSearchName").val(ui.item.label);
                return false;
            },
            minLength: 1
        });

        jQuery(".inputItem").keydown(function (event) {
            // Allow: backspace, delete, tab, escape, enter and .
            if (jQuery.inArray(event.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
                // Allow: Ctrl+A
                (event.keyCode == 65 && event.ctrlKey === true) ||
                // Allow: home, end, left, right
                (event.keyCode >= 35 && event.keyCode <= 40)) {

                return;
            }
            else {
                // Ensure that it is a number and stop the keypress
                if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                    event.preventDefault();
                }
                else {
                    var $focused = $(':focus');
                    if ($focused.val().length >= 10) {
                        $focused.keydown(function (event) {
                            event.preventDefault();
                        })
                    }
                }
            }
        });

        $(document).on("click", ".edit", function () {
            var str = $(this).attr("id").split("_");
            id = str[1];

            var spanName = "#spanName_" + id;
            var Name = "#Name_" + id;
            var spanDescription = "#spanDescription_" + id;
            var Description = "#Description_" + id;

            $(Name).val($(spanName).text());
            $(Description).val($(spanDescription).text());

            $(spanName).hide();
            $(Name).show();
            $(spanDescription).hide();
            $(Description).show();

            $(this).hide();
            $("#Update_" + id).show();
            $("#Cancel_" + id).show();

            return false;
        });

        $(document).on("click", ".update", function () {
            var str = $(this).attr("id").split("_");
            id = str[1];

            var nameVal = $("#Name_" + id).val();
            var descriptionVal = $("#Description_" + id).val();
            var typeVal = $("#Type_" + id).val();
            var unitVal = $("#Unit_" + id).val();

            if (id != "") {
                $.ajax({
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    url: '@Url.Action("Update", "Stone")',
                    data: { "id": id, "name": nameVal, "description": descriptionVal },
                    dataType: "json",
                    beforeSend: function () {//alert(id);
                    },
                    success: function (data) {
                        if (data.result == true) {
                            $("#Update_" + id).hide();
                            $("#Cancel_" + id).hide();
                            $("#Edit_" + id).show();

                            var spanName = "#spanName_" + id;
                            var Name = "#Name_" + id;
                            var spanDescription = "#spanDescription_" + id;
                            var Description = "#Description_" + id;

                            $(spanName).show();
                            $(Name).hide();
                            $(spanDescription).show();
                            $(Description).hide();

                            $(spanName).text($(Name).val());
                            $(spanDescription).text($(Description).val());
                        }
                        else {
                            alert('There is some error');
                        }
                    }
                });
            }

            return false;
        });

        $(document).on("click", ".cancel", function () {
            var str = $(this).attr("id").split("_");
            id = str[1];

            var spanId = "#spanId_" + id;
            var Id = "#Id_" + id;
            var spanName = "#spanName_" + id;
            var Name = "#Name_" + id;
            var spanDescription = "#spanDescription_" + id;
            var Description = "#Description_" + id;

            $(spanId).show();
            $(Id).hide();
            $(spanName).show();
            $(Name).hide();
            $(spanDescription).show();
            $(Description).hide();

            $(this).hide();
            $("#Edit_" + id).show();
            $("#Update_" + id).hide();

            return false;
        });
    </script>

    @*get data*@
    <script type="text/javascript">

        $("#btnClear").click(function () {
            $("#stoneArea").empty();
        });

        $("#btnAddMore").click(function () {
            var flag = 0;

            // get data stone
            MyStone.init();

            var countAllItems = 0;
            var countCompletedItems = 0;
            $('.pStoneTag').each(function () {
                countAllItems++;

                var Id = $(this).children('.Id').val();
                var Name = $(this).children('.Name').val();
                var Description = $(this).children('.Description').val();
                var Type = $(this).children('.Type').val();
                var Unit = $(this).children('.Unit').val();
                var Weight = $(this).children('.Weight').val();
                var Quantity = $(this).children('.Quantity').val();
                var errorAdd = $(this).next("p").children(".Error");

                if (!Id || !Unit) {
                    var textError = "";
                    if (!Id) {
                        textError += "Stone Id";
                    }
                    if (!Unit) {
                        if (textError.length > 0) {
                            textError += ", ";
                        }
                        textError += "Unit";
                    }

                    textError += " must to be filled.";

                    $(errorAdd).text(textError).show().fadeOut(5000);
                } else {

                    var strError1, strError2, strError3, strError;
                    strError1 = "";
                    strError2 = "";
                    strError3 = "";
                    strError = "";
                    // check
                    $.ajax({
                        type: "GET",
                        contentType: "application/json; charset=utf-8",
                        url: '@Url.Action("IsStoneExisted", "Stone")',
                        data: { "id": Id },
                        dataType: "json",
                        async: false,
                        beforeSend: function () {//alert();
                        },
                        success: function (data) {
                            if (data.result == true) {
                                countCompletedItems++;
                            } else {
                                if (Type.length > 0) {
                                    $.ajax({
                                        type: "GET",
                                        contentType: "application/json; charset=utf-8",
                                        url: '@Url.Action("IsTypeNameExisted", "Stone")',
                                        data: { "typeName": Type },
                                        dataType: "json",
                                        async: false,
                                        beforeSend: function () {//alert();
                                        },
                                        success: function (data) {
                                            if (data.result == false) {
                                                //$(errorAdd).text("The Type hasn't existed in the system yet. Please check again.").show().fadeOut(5000);
                                                strError2 = "Type";
                                                flag = 3;
                                            }
                                        }
                                    });
                                }

                                $.ajax({
                                    type: "GET",
                                    contentType: "application/json; charset=utf-8",
                                    url: '@Url.Action("IsUnitNameExisted", "Stone")',
                                    data: { "unitName": Unit },
                                    dataType: "json",
                                    async: false,
                                    beforeSend: function () {//alert();
                                    },
                                    success: function (data) {
                                        if (data.result == false) {
                                            //$(errorAdd).text("The Type hasn't existed in the system yet. Please check again.").show().fadeOut(5000);
                                            strError3 = "Unit";
                                            flag = 3;
                                        }
                                    }
                                });

                                if (flag != 0) {
                                    strError = strError1;
                                    if (strError1.length > 0) {
                                        strError += " has existed in the system.";
                                    }
                                    if (strError.length > 0 && strError2.length > 0) {
                                        strError += ", " + strError2;
                                    } else {
                                        strError += strError2;
                                    }
                                    if (strError.length > 0 && strError3.length > 0) {
                                        strError += ", " + strError3;
                                    } else {
                                        strError += strError3;
                                    }
                                    if (flag == 3) {
                                        strError += " hasn't existed in the system yet. Please check again.";
                                    }
                                    $(errorAdd).text(strError).show().fadeOut(5000);
                                }

                                if (flag == 0) {
                                    var stone = new StoneViewModel(Id, Name, Description, Type, Unit, Weight, Quantity);
                                    MyStone.Data.push(stone);
                                    countCompletedItems++;
                                }
                            }
                        },
                    });
                }
            });

            if (flag == 0 && countAllItems == countCompletedItems) {
                if (MyStone.Data.length == 0) {
                    $("#notification").text("There is no stone. Please check again.").show().fadeOut(5000);
                    return;
                } else {
                    AllPost.DataStone = MyStone.Data;
                    AllPost.post();
                }
            }
        });

        // function stone
        function StoneViewModel(Id, Name, Description, Type, Unit, Weight, Quantity) {
            var self = this;
            self.Id = Id;
            self.Name = Name;
            self.Description = Description;
            self.Type = Type;
            self.Unit = Unit;
            self.Quantity = Quantity;
            self.Weight = Weight;
        }

        var MyStone = function () {
            return {

                init: function () {
                    MyStone.Data = new Array();
                },
            }
        }();

        // all post
        var AllPost = function () {
            return {
                PostUrl: null,

                post: function () {
                    postData = { stones: AllPost.DataStone };
                    $.ajax({
                        url: '/Stone/SaveToDB',
                        type: 'POST',
                        dataType: 'json',
                        data: JSON.stringify(postData),
                        contentType: 'application/json; charset=utf-8',
                        success: function (data) {
                            //alert(data.responseText);
                            if (data.result == false) {
                                alert("Some Type fields are invalid");
                            } else {

                                for (var i = 0; i < postData.stones.length; i++) {
                                    var id = postData.stones[i].Id;
                                    var name = postData.stones[i].Name;
                                    var description = postData.stones[i].Description;
                                    var typeName = postData.stones[i].Type;
                                    var unitName = postData.stones[i].Unit;
                                    var weight = postData.stones[i].Weight;
                                    var quantity = postData.stones[i].Quantity;

                                    // add stone to table
                                    var className = $("#stoneListDiv").find("tbody").find("tr:last").hasClass("row");

                                    if (className == true) {
                                        className = "altRow";
                                    } else {
                                        className = "row";
                                    }

                                    var newRow = '<tr class="' + className + '"><td><div id="spanId_' + id + '" style="width: 200px; text-align: center;">' + id + '</div></td>'
                                        + '<td><div style="width: 200px; text-align: center;"><span id="spanName_' + id + '">' + name + '</span><input id="Name_' + id + '" style="display:none; width: 120px" type="text"></div></td>'
                                        + '<td><div style="width: 150px; text-align: center;"><span id="spanDescription_' + id + '">' + description + '</span><input id="Description_' + id + '" style="display:none; width: 120px" type="text"></div></td>'
                                        + '<td><div id="spanId_' + id + '" style="width: 100px; text-align: center;">' + typeName + '</div></td>'
                                        + '<td><div id="spanId_' + id + '" style="width: 100px; text-align: center;">' + unitName + '</div></td>'
                                        + '<td><div id="spanId_' + id + '" style="width: 100px; text-align: center;">' + weight + '</div></td>'
                                        + '<td><div id="spanId_' + id + '" style="width: 100px; text-align: center;">' + quantity + '</div></td>'
                                        + '<td><div style="width: 150px; text-align: center;"><a href="#" id="Edit_' + id + '" style="margin: 5px" class="edit">Edit</a><a href="#" id="Update_' + id + '" style="display:none; margin: 5px" class="update">Update</a><a href="#" id="Cancel_' + id + '" style="display:none; margin: 5px" class="cancel">Cancel</a></div></td>' + "</tr>";

                                    $("#stoneListDiv").find("table tbody:last").append(newRow);
                                }
                            }

                            $("#stoneArea").empty();

                            alert("Add stones successfully.");
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            //alert(data.responseText);
                        }
                    });
                }

            }
        }();
    </script>

    @*Add stone Event Handler*@
    <script type="text/javascript">
        var index = 1;

        $('#btnAddNewRow').click(function () {
            index += 1;
            addStone(index, "", "", "", "", "", "", "");
        });

        // add stone function
        function addStone(index, Id, Name, Description, Type, Unit, Weight, Quantity) {
            $('#stoneArea').append('<p class="pStoneTag">' +
                           '<input type="text" class="Id requiredInput textInput" id="iId' + index + '"placeholder="Stone Id" required >' +
                           '<input type="text" class="Name textInput" id="iName' + index + '"placeholder="Name">' +
                           '<input type="text" class="Description textInput" id="iDescription' + index + '"placeholder="Description">' +
                           '<input type="text" class="Type shortTextInput" id="iType' + index + '"placeholder="Type">' +
                           '<input type="text" class="Unit requiredInput shortTextInput" id="iUnit' + index + '"placeholder="Unit" required>' +
                           '<input type = "number" min="0" step = "any" class="Weight inputItem" id="iWeight' + index + '" placeholder="Weight">' +
                           '<input type = "number" min="0" class="Quantity inputItem" id="iQuantity' + index + '" placeholder="Quantity">' +
                           '<a href="#" id="remove">Remove </a> </p><p><span style="display: none; color: red;" class="Error" id="errorAdd' + index + '"></span></p>');

            // remove additional elements
            $(document).on("click", "#remove ", function () {
                $(this).parents('p').remove();
                return false;
            });

            $("#iId" + index).val(Id);
            $("#iName" + index).val(Name);
            $("#iDescription" + index).val(Description);
            $("#iType" + index).val(Type);
            $("#iUnit" + index).val(Unit);
            $("#iWeight" + index).val(Weight);
            $("#iQuantity" + index).val(Quantity);

            var stoneId = $("#iId" + index);
            var errorAdd = $("#errorAdd" + index);
            $(stoneId).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/Stone/GetStones',
                        data: { query: request.term },
                        dataType: 'json',
                        type: 'GET',
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item,
                                    value: item
                                }
                            }));
                        },
                    })
                },
                messages: {
                    noResults: '',
                    results: function () { }
                },
                select: function (event, ui) {
                    $(stoneId).val(ui.item.label);
                    return false;
                },
                minLength: 1
            });

            $(stoneId).blur(function () {
                var Id = $(this).val();

                $.ajax({
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    url: '@Url.Action("IsStoneExisted", "Stone")',
                    data: { "id": Id },
                    dataType: "json",
                    beforeSend: function () {//alert();
                    },
                    success: function (data) {
                        if (data.result == true) {
                            $(errorAdd).text("Stone id has existed in the system. Please check again.").show().fadeOut(5000);
                        }
                    }
                });
            });

            var typeEle = $("#iType" + index);
            $(typeEle).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/Stone/GetTypes',
                        data: { query: request.term },
                        dataType: 'json',
                        type: 'GET',
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item.Name,
                                    value: item.Name
                                }
                            }));
                        },
                    })
                },
                messages: {
                    noResults: '',
                    results: function () { }
                },
                select: function (event, ui) {
                    $(typeEle).val(ui.item.label);
                    return false;
                },
                minLength: 1
            });

            $(typeEle).blur(function () {
                var TypeName = $(this).val();

                if (TypeName.length > 0) {
                    $.ajax({
                        type: "GET",
                        contentType: "application/json; charset=utf-8",
                        url: '@Url.Action("IsTypeNameExisted", "Stone")',
                        data: { "typeName": TypeName },
                        dataType: "json",
                        beforeSend: function () {//alert();
                        },
                        success: function (data) {
                            if (data.result == false) {
                                $(errorAdd).text("The Type hasn't existed in the system yet. Please check again.").show().fadeOut(5000);
                            }
                        }
                    });
                }
            });

            var unitEle = $("#iUnit" + index);
            $(unitEle).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/Stone/GetUnits',
                        data: { query: request.term },
                        dataType: 'json',
                        type: 'GET',
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item.Name,
                                    value: item.Name
                                }
                            }));
                        },
                    })
                },
                messages: {
                    noResults: '',
                    results: function () { }
                },
                select: function (event, ui) {
                    $(unitEle).val(ui.item.label);
                    return false;
                },
                minLength: 1
            });

            $(unitEle).blur(function () {
                var UnitName = $(this).val();

                $.ajax({
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    url: '@Url.Action("IsUnitNameExisted", "Stone")',
                    data: { "unitName": UnitName },
                    dataType: "json",
                    beforeSend: function () {//alert();
                    },
                    success: function (data) {
                        if (data.result == false) {
                            $(errorAdd).text("The Unit hasn't existed in the system yet. Please check again.").show().fadeOut(5000);
                        }
                    }
                });
            });

            jQuery(".inputItem").keydown(function (event) {
                // Allow: backspace, delete, tab, escape, enter and .
                if (jQuery.inArray(event.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
                    // Allow: Ctrl+A
                    (event.keyCode == 65 && event.ctrlKey === true) ||
                    // Allow: home, end, left, right
                    (event.keyCode >= 35 && event.keyCode <= 40)) {

                    return;
                }
                else {
                    // Ensure that it is a number and stop the keypress
                    if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                        event.preventDefault();
                    }
                    else {
                        var $focused = $(':focus');
                        if ($focused.val().length >= 10) {
                            $focused.keydown(function (event) {
                                event.preventDefault();
                            })
                        }
                    }
                }
            });

            /*
            var size = $("#iSize" + index);
            var quantity = $("#iQuantity" + index);
            $(size).blur(function () {
                var value = $(this).val();

                if (value.length == 0 || parseInt(value) == 0) {
                    $(errorAdd).text("The field is required and value has to be greater than 0. Please check again.").show().fadeOut(5000);
                }
            });
            $(quantity).blur(function () {
                var value = $(this).val();

                if (value.length == 0 || parseInt(value) == 0) {
                    $(errorAdd).text("The field is required and value has to be greater than 0. Please check again.").show().fadeOut(5000);
                }
            });*/
        }

        $("#contentPaste").on("paste", function (e) {
            // only execute when after finishing paste process
            setTimeout(function () {
                var text = "";

                // get elements
                var dataContainer = document.getElementById("contentPaste");
                var data = dataContainer.getElementsByTagName("table")[0];
                var listRows = data.getElementsByTagName("tr");

                for (var i = 0; i < listRows.length; i++) {
                    var listCols = listRows[i].getElementsByTagName("td");

                    //text += listCols[0].innerHTML + ", " + listCols[1].innerHTML + ";\n";
                    addStone(index,
                        listCols[0] == null ? "" : listCols[0].innerText,
                        listCols[1] == null ? "" : listCols[1].innerText,
                        listCols[2] == null ? "" : listCols[2].innerText,
                        listCols[3] == null ? "" : listCols[3].innerText,
                        listCols[4] == null ? "" : listCols[4].innerText,
                        listCols[5] == null ? "" : listCols[5].innerText,
                        listCols[6] == null ? "" : listCols[6].innerText);

                    index++;
                }

                //data.remove();
                dataContainer.innerHTML = "Paste here...";

                // get data
                //alert(text);
            },
                0
            );
        });

        $(function () {
            window.alert = function (message) {
                $(document.createElement('div'))
                    .attr({ title: 'Information', 'class': 'alert' })
                    .html(message)
                    .dialog({
                        buttons: { OK: function () { $(this).dialog('close'); } },
                        close: function () { $(this).remove(); },
                        draggable: true,
                        modal: true,
                        resizable: false,
                        width: 'auto'
                    });
            };
        });
    </script>
}